package com.yaorange.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yaorange.common.core.exception.ServiceException;
import com.yaorange.teaching.bo.TeacherSechedulingListBo;
import com.yaorange.teaching.domain.YaClass;
import com.yaorange.teaching.domain.YaTeacher;
import com.yaorange.teaching.domain.YaTeachingPlan;
import com.yaorange.teaching.mapper.YaTeachingPlanMapper;
import com.yaorange.teaching.service.IYaClassService;
import com.yaorange.teaching.service.IYaTeacherSechedulingService;
import com.yaorange.teaching.service.IYaTeacherService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/12/2
 */
@Service
public class YaTeacherSechedulingServiceImpl implements IYaTeacherSechedulingService {

    @Autowired
    private YaTeachingPlanMapper yaTeachingPlanMapper;

    @Autowired
    private IYaTeacherService yaTeacherService;

    @Autowired
    private IYaClassService yaClassService;

    @Override
    @Transactional(readOnly = true)
    public TeacherSechedulingListBo selectTeachingPlanList() {

        //课表
        List<Map<String, Object>> teachingPlantList;
        //查询到所有班级对应的课表日期
        List<String> dateList = yaTeachingPlanMapper.selectTeachingPlanDateList();
        if (CollectionUtils.isEmpty(dateList)) {
            throw new ServiceException("目前所有班级已经结班");
        }

        //查询在职老师列表
        YaTeacher yaTeacher = new YaTeacher();
        //1-在职 2-离职 3-退休
        yaTeacher.setStatus(1);
        List<YaTeacher> teachingList = yaTeacherService.selectYaTeacherList(yaTeacher);

        //查询正常班级列表
        List<YaClass> classList = yaClassService.selectYaClassOptions();

        //所有班级的课表 key:班级+日期（java46-2024-12-01） value:课表
        Map<String, Map<String, Object>> dateTeachingPlanMap = yaTeachingPlanMapper.selectYaAllTeachingPlanList().stream().collect(Collectors.toMap(map -> map.get("class_name").toString() +"-"+ map.get("date").toString(), map -> map));


        teachingPlantList = dateList.stream()
            .map(date -> {
                Map<String, Object> dateMap = new HashMap<>();
                dateMap.put("date", date);
                dateMap.put("weekday", getWeekDayDesc(date));

                classList.forEach(classes -> {
                    String className = classes.getClassName();
                    String key = className + "-" + date;

                    Map<String, Object> teachingPlan = dateTeachingPlanMap.getOrDefault(key, Collections.emptyMap());
                    dateMap.put(className, createTeachingPlanValue(teachingPlan));
                });

                return dateMap;
            })
            .collect(Collectors.toList());

        return TeacherSechedulingListBo.builder()
            .teachingPlanList(teachingPlantList)
            .teacherOptions(convertToOptions(teachingList, YaTeacher::getName))
            .classOptions(convertToOptions(classList, YaClass::getClassName))
            .build();
    }

    private static String getWeekDayDesc(String date) {
        int value = LocalDate.parse(date).getDayOfWeek().getValue();
        switch (value) {
            case 1:
                return "星期一";
            case 2:
                return "星期二";
            case 3:
                return "星期三";
            case 4:
                return "星期四";
            case 5:
                return "星期五";
            case 6:
                return "星期六";
        }
        return "星期日";
    }

    // 提取创建教学计划值的方法
    private Map<String, String> createTeachingPlanValue(Map<String, Object> teachingPlan) {
        Map<String, String> value = new HashMap<>();
        value.put("content", String.valueOf(teachingPlan.getOrDefault("course_content", "")));
        value.put("teacher", String.valueOf(teachingPlan.getOrDefault("teacher", "")));
        return value;
    }

    // 通用的选项转换方法
    private <T> List<Map<String, String>> convertToOptions(List<T> items, Function<T, String> valueMapper) {
        return items.stream()
            .map(item -> {
                Map<String, String> option = new HashMap<>();
                String value = valueMapper.apply(item);
                option.put("label", value);
                option.put("value", value);
                return option;
            })
            .collect(Collectors.toList());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTeacherAssignment(String className, String teacher, String date) {
        //先检查该老师对应date是否有课
        LambdaQueryWrapper<YaTeachingPlan> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(YaTeachingPlan::getDate, date);
        objectLambdaQueryWrapper.eq(YaTeachingPlan::getTeacher, teacher);

        YaTeachingPlan tp = yaTeachingPlanMapper.selectOne(objectLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(tp)) {
            throw new RuntimeException(teacher+"的"+date+"已经分配给了"+tp.getClassName());
        }
        LambdaUpdateWrapper<YaTeachingPlan> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(YaTeachingPlan::getDate, date);
        lambdaUpdateWrapper.eq(YaTeachingPlan::getClassName, className);
        YaTeachingPlan newTp = YaTeachingPlan.builder()
                .teacher(teacher)
                .build();
        yaTeachingPlanMapper.update(newTp, lambdaUpdateWrapper);
        return 1;
    }
}
